package com.youlai.netty.service.tcp.server;

import com.youlai.netty.service.handler.HTTPHandler;
import com.youlai.netty.service.tcp.BootNettyChannelInboundHandlerAdapter;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.HttpServerCodec;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * @author zc
 * @date 2023-02-04 20:07
 */
@Slf4j
public class HTTPServer {

    public void bind(int port){
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap
                    .group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<NioSocketChannel>() {
                        protected void initChannel(NioSocketChannel ch) {
                            ChannelPipeline pipeline = ch.pipeline();
                            //1.Netty提供的针对Http的编解码
                            pipeline.addLast(new HttpServerCodec());
                            //2.自定义处理Http的业务Handler
                            pipeline.addLast(new HTTPHandler());
                        }
                    });
            ChannelFuture f = serverBootstrap.bind(port).sync();
            if(f.isSuccess()){
                log.info("HTTP服务启动成功,端口:{}",port);
                /**
                 * 等待服务器监听端口关闭
                 */
                f.channel().closeFuture().sync();
            }else{
                serverBootstrap.config().group().schedule(new Runnable() {
                    @Override
                    public void run() {
                        bind(port);
                    }
                },5, TimeUnit.SECONDS);
                log.error("创建HTTP服务失败:{}",f.cause().getMessage());
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
